package cn.anecansaitin.whimsy.common.enchantment;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.entity.PhantasmArrow;
import cn.anecansaitin.whimsy.common.event.ArrowHitLivingEntityEvent;
import cn.anecansaitin.whimsy.common.register.ModEnchantments;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.projectile.AbstractArrow;
import net.minecraft.world.item.BowItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;

/**
 * 幻影箭，在箭击中敌人后生成幻影箭追踪攻击敌人
 */
@Mod.EventBusSubscriber(modid = Whimsy.MODID)
public class Phantasm extends Enchantment {
    public Phantasm() {
        super(Rarity.VERY_RARE, EnchantmentCategory.BOW, new EquipmentSlot[]{EquipmentSlot.MAINHAND});
    }

    @Override
    public boolean isTreasureOnly() {
        return true;
    }

    @Override
    public boolean isTradeable() {
        return false;
    }

    @Override
    public boolean isDiscoverable() {
        return false;
    }

    @SubscribeEvent
    public static void onHit(ArrowHitLivingEntityEvent event) {
        LivingEntity enemy = event.getEntity();

        if (enemy.level().isClientSide() || !enemy.isAlive()) {
            return;
        }

        AbstractArrow arrow = event.getArrow();

        if (arrow instanceof PhantasmArrow && !arrow.getTags().contains("bow_shot")) {
            return;
        }

        Entity owner = arrow.getOwner();

        if (!(owner instanceof LivingEntity) || enemy.is(owner)) {
            return;
        }

        ItemStack bow = ((LivingEntity) owner).getMainHandItem();

        if (!(bow.getItem() instanceof BowItem)) {
            return;
        }

        int lvl = bow.getEnchantmentLevel(ModEnchantments.PHANTASM.get());

        if (lvl < 1) {
            return;
        }

        PhantasmArrow phantasmArrow = new PhantasmArrow((LivingEntity) owner, enemy);
        phantasmArrow.setBaseDamage(arrow.getBaseDamage() / 2);
        phantasmArrow.shootFromRotation(owner, owner.getXRot(), owner.getYRot(), 0, 3, 1);
        owner.level().addFreshEntity(phantasmArrow);
    }
}
